package com.example.shudi.sdkdemo.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;

import java.io.File;

/**
 * Created by zhangleilei on 2018/10/17.
 */

public class CameraUtils {


    public static final int REQUEST_TAKE_PICTURE = 2;
    public static final int REQUEST_CHOOSE_ALBUM = 3;

    public static String getPhotoFilePath() {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/temp" + ".jpg";
    }

    public static void takePhoto(Activity context) {
        Uri currentPhotoUri = getUriFromPath(context, getPhotoFilePath());
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, currentPhotoUri);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivityForResult(intent, REQUEST_TAKE_PICTURE);
        }
    }


    public static Uri getUriFromPath(Context context, String filePath) {
        File file = new File(filePath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".uri", file);
        } else {
            return Uri.fromFile(file);
        }
    }

    public static Bitmap getCroppedBitmap(Bitmap bitmap, int imageSize) {
        Bitmap croppedBitmap = Bitmap.createBitmap(imageSize, imageSize, Bitmap.Config.ARGB_8888);
        Matrix transformationMatrix = getPhotoBitmapTransformationMatrix(bitmap, imageSize);
        Canvas canvas = new Canvas(croppedBitmap);
        canvas.drawBitmap(bitmap, transformationMatrix, null);
        return croppedBitmap;
    }

    private static Matrix getPhotoBitmapTransformationMatrix(Bitmap bitmap, int imageSize) {
        Matrix frameToCropTransformationMatrix = getTransformationMatrix(
                bitmap.getWidth(), bitmap.getHeight(),
                imageSize, imageSize,
                0, true);

        Matrix cropToFrameTransformationMatrix = new Matrix();
        frameToCropTransformationMatrix.invert(cropToFrameTransformationMatrix);
        return frameToCropTransformationMatrix;
    }


    private static Matrix getTransformationMatrix(
            int srcWidth,
            int srcHeight,
            int dstWidth,
            int dstHeight,
            int applyRotation,
            boolean maintainAspectRatio) {
        Matrix matrix = new Matrix();

        // Translate so center of image is at origin.
        matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f);

        // Rotate around origin.
        matrix.postRotate((float) applyRotation);

        // Account for the already applied rotation, if any, and then determine how
        // much scaling is needed for each axis.
        boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0;

        int inWidth = srcWidth;
        int inHeight = srcHeight;
        if (transpose) {
            inWidth = srcHeight;
            inHeight = srcWidth;
        }

        // Apply scaling if necessary.
        if (inWidth != dstWidth || inHeight != dstHeight) {
            float scaleFactorX = dstWidth / (float) inWidth;
            float scaleFactorY = dstHeight / (float) inHeight;

            if (maintainAspectRatio) { // Scale by minimum factor so that dst is filled completely while
                // maintaining the aspect ratio. Some image may fall off the edge.
                float scaleFactor = Math.max(scaleFactorX, scaleFactorY);
                matrix.postScale(scaleFactor, scaleFactor);
            } else { // Scale exactly to fill dst from src.
                matrix.postScale(scaleFactorX, scaleFactorY);
            }
        }

        // Translate back from origin centered reference to destination frame.
        matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f);

        return matrix;
    }
}
